//
//  FLMakeAudioViewController.m
//  FeeLing
//
//  Created by 乔光玉 on 2019/1/11.
//  Copyright © 2019年 大仙儿飘. All rights reserved.
//
#import "FLRceondNameView.h"
#import "FLAnainNameView.h"
#import "SKVoiceWaveView.h"
#import "SFDualWaySlider.h"
#import "FLAudioObject.h"
#import "FLAudioMusicDBManager.h"
#import "FLMakeAudioViewController.h"

@interface FLMakeAudioViewController ()<UIGestureRecognizerDelegate>
{
    CGFloat statr;
    CGFloat end;
    BOOL isdayufourty;
    FLAnainNameView * _sanainview;
    BOOL _isPlaying;
}
typedef void(^success)(BOOL ret);
@property (nonatomic, copy)success block;
@property (nonatomic,strong) AVPlayerItem *playerItem;
@property (nonatomic,strong) AVPlayer *auPlayer;

@property(nonatomic,strong) UIButton * playButton;
@property(nonatomic,strong) UIButton * bringButton;
@property(nonatomic,strong) UILabel * begintime;
@property(nonatomic,strong) UILabel * endtime;
@property(nonatomic,strong) UILabel * cutLabel;
@property(nonatomic,strong)NSURL * songURL;
@property(nonatomic,strong)NSString * musicPath ;
@property (nonatomic,strong)FLAudioObject * model;
@property(nonatomic,strong) UIButton * backButton;
@property(nonatomic,strong)UIView * navView;
@property(nonatomic,strong)UILabel * navLabel;

@end

@implementation FLMakeAudioViewController

-(void)backButtonclick{
    
    if (_isPlaying) {
        
        [self.auPlayer pause];
        
    }
    [self.navigationController popToRootViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = YES;
}
-(void)viewWillDisappear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = [UIColor colorWithHexString:@"#2B2D5C"];
    
    if (self.model==nil) {
        self.model = [[FLAudioObject alloc]init];
        
    }
    self.navView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 64)];
    self.navView.backgroundColor = [UIColor colorWithHexString:@"32346A"];
    [self.view addSubview:self.navView];
    
    self.navLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 30, SCREENWIDTH, 25)];
    self.navLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    self.navLabel.textAlignment = NSTextAlignmentCenter;
    self.navLabel.textColor = [UIColor whiteColor];
    self.navLabel.text = NSLocalizedString(@"videoLabeltext", nil);
    [self.view addSubview:self.navLabel];
    
    _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_backButton setImage:[UIImage imageNamed:@"返回首页_slices"] forState:UIControlStateNormal];
    _backButton.frame = CGRectMake(12, 29, 27, 27);
    [_backButton addTarget:self action:@selector(backButtonclick) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:_backButton];
    if (SCREENHEIGHT>800) {
        
        self.navView.frame =CGRectMake(0, 0, SCREENWIDTH, 84);
        self.navLabel.frame =CGRectMake(0, 30+20, SCREENWIDTH, 25);
        _backButton.frame = CGRectMake(12, 29+20, 27, 27);
    }
    UIView *bottomview = [[UIView alloc] init];
    bottomview.frame = CGRectMake(15,84*SCREENHEIGHT/667,SCREENWIDTH-30,205*SCREENHEIGHT/667);
    
    bottomview.backgroundColor = [UIColor colorWithRed:36/255.0 green:35/255.0 blue:79/255.0 alpha:1.0];
    bottomview.layer.cornerRadius = 8;
    bottomview.clipsToBounds = YES;
    [self.view addSubview:bottomview];
    
    
    self.begintime = [[UILabel alloc]initWithFrame:CGRectMake(60, 21*SCREENHEIGHT/667, 40, 14)];
    self.begintime.text = @"00:00";
    self.begintime.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.begintime.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.begintime.textAlignment= NSTextAlignmentLeft;
    [bottomview addSubview:self.begintime];
    statr =0;
    
    self.endtime = [[UILabel alloc]initWithFrame:CGRectMake(bottomview.width-61-40, 21*SCREENHEIGHT/667, 40, 14)];
    CGFloat ttime =CMTimeGetSeconds(self.avasset.duration);
    
    self.endtime.text =[self getMMSSFromSS:(int)ttime];
    self.endtime.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.endtime.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.endtime.textAlignment= NSTextAlignmentRight;
    [bottomview addSubview:self.endtime];
    
    self.cutLabel = [[UILabel alloc]initWithFrame:CGRectMake(bottomview.width-61-40, 21*SCREENHEIGHT/667+70, 40, 14)];
    self.cutLabel.text =[self getMMSSFromSS:(int)ttime];
    self.cutLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 10];
    self.cutLabel.textColor = [UIColor colorWithHexString:@"#B19ADA"];
    self.cutLabel.textAlignment= NSTextAlignmentRight;
    [bottomview addSubview:self.cutLabel];
    UIView *waveViewview = [[UIView alloc] init];
    waveViewview.frame = CGRectMake(45, self.endtime.bottom+6, bottomview.width-90, 44);
    
    waveViewview.backgroundColor = [UIColor colorWithRed:129/255.0 green:132/255.0 blue:193/255.0 alpha:1.0];
    waveViewview.layer.cornerRadius = 8;
    waveViewview.clipsToBounds = YES;
    [bottomview addSubview:waveViewview];
    
    SKVoiceWaveView *waveView = [[SKVoiceWaveView alloc]initWithFrame:CGRectMake(45, self.endtime.bottom+6, bottomview.width-90, 44)];
    waveView.backgroundColor = [UIColor clearColor];
    //waveView.path = [[NSBundle mainBundle] pathForResource:@"beat" ofType:@"aiff" inDirectory:nil];//指定路径
    //  waveView.url = [NSBundle URLForResource:@"李荣浩 - 老街" withExtension:@"mp3" subdirectory:nil inBundleWithURL:[NSBundle mainBundle].bundleURL];//指定URL
    waveView.asset = self.avasset; //指定媒体
    
    waveView.lineWidth = 0;//线宽，默认0，0则为连续的视图，可测试
    waveView.lineColor = [UIColor colorWithHexString:@"#6E7370"];//颜色，默认灰色
    waveView.lineDistance = 4;//线之间的距离，默认4
    [bottomview addSubview:waveView];
    
   
    
    double max =CMTimeGetSeconds(self.avasset.duration) ;
    
    
    SFDualWaySlider *slider = [[SFDualWaySlider alloc] initWithFrame:CGRectMake(45, self.endtime.bottom+6, bottomview.width-90, 44) minValue:0 maxValue:(int)max blockSpaceValue:0];
    
    slider.sliderValueChanged = ^(CGFloat minValue, CGFloat maxValue) {
        if (isdayufourty) {
            isdayufourty = NO;
            
            return ;
        }
        int difference = (int)maxValue-(int)minValue;
        self.begintime.text = [self getMMSSFromSS:(int)minValue];
        self.endtime.text =  [self getMMSSFromSS:(int)maxValue];
        self.cutLabel.text=[self getMMSSFromSS:difference];
        statr = (int)minValue;
        end = (int)maxValue;
    };
    if (max>40) {
        isdayufourty = YES;
        end = 40.00;
        slider.currentMaxValue = 40;
        self.cutLabel.text=@"00:40";
    }else{
        isdayufourty =NO;
        end = max;
    }
    
    
    
    
    [bottomview addSubview:slider];
    
    self.bringButton = [UIButton new];
    self.bringButton.frame =CGRectMake(bottomview.width/2-255/2,141*SCREENHEIGHT/667,255,44);
    CAGradientLayer *glbringButton = [CAGradientLayer layer];
    glbringButton.frame = CGRectMake(0,0,255,44);
    glbringButton.startPoint = CGPointMake(0.08, 0.18);
    glbringButton.endPoint = CGPointMake(1, 0.89);
    glbringButton.colors = @[(__bridge id)[UIColor colorWithRed:252/255.0 green:86/255.0 blue:142/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:252/255.0 green:86/255.0 blue:142/255.0 alpha:1.0].CGColor, (__bridge id)[UIColor colorWithRed:246/255.0 green:55/255.0 blue:51/255.0 alpha:1.0].CGColor];
    glbringButton.locations = @[@(0), @(0), @(1.0f)];
    glbringButton.cornerRadius = 22;
    [self.bringButton.layer insertSublayer:glbringButton atIndex:0];
    [self.bringButton setTitle:NSLocalizedString(@"bringButtontitle", nil) forState:UIControlStateNormal];
    [self.bringButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.bringButton.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size: 18];
    
    [self.bringButton addTarget:self action:@selector(bringButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomview addSubview:self.bringButton];
    
    self.playButton = [UIButton new];
    self.playButton.frame =CGRectMake(7,waveView.centerY-16,32,32);
    [self.playButton setImage:[UIImage imageNamed:@"剪裁音频播放"] forState:UIControlStateNormal];
    [self.playButton setImage:[UIImage imageNamed:@"剪裁音频暂停"] forState:UIControlStateSelected];
    [self.playButton addTarget:self action:@selector(palyButtonclick:) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomview addSubview:self.playButton];
    
    UIImageView * bottomimageview = [[UIImageView alloc]initWithFrame:CGRectMake(0, SCREENHEIGHT-56, SCREENWIDTH, 56)];
    [bottomimageview setImage:[UIImage imageNamed:@"我的背景"]];
    [self.view addSubview:bottomimageview];
    
}
//传入 秒  得到  xx分钟xx秒
-(NSString *)getMMSSFromSS:(NSInteger )seconds{
    
    
    
    //format of minute
    NSString *str_minute ;
    if (seconds/60>=10) {
        str_minute = [NSString stringWithFormat:@"%ld",seconds/60];
    }else{
        str_minute = [NSString stringWithFormat:@"0%ld",seconds/60];
    }
    
    //format of second
    NSString *str_second;
    if (seconds%60>=10) {
        str_second = [NSString stringWithFormat:@"%ld",seconds%60];
    }else{
        str_second = [NSString stringWithFormat:@"0%ld",seconds%60];
    }
    
    //format of time
    NSString *format_time = [NSString stringWithFormat:@"%@:%@",str_minute,str_second];
    
    NSLog(@"format_time : %@",format_time);
    
    return format_time;
    
}

-(void)bringButtonclick:(UIButton *)sender{
    
    
    __weak typeof(self) weakself = self;
    _sanainview = [[FLAnainNameView alloc]initWithFrame:[UIScreen mainScreen].bounds];
    self-> _sanainview.cancelBlock = ^(UIButton * sender) {
        
        
        __strong __typeof(self) strongSelf = weakself;
        [strongSelf->_sanainview removeFromSuperview];
        
        
    };
    
    self-> _sanainview.tureBlock = ^(UIButton * _Nonnull button, NSString * _Nonnull text) {
        
        if (text.length) {
            if ([[FLAudioMusicDBManager sharedManager] isExistAudio:text]) {
                
                [MBProgressHUD showError:NSLocalizedString(@"mingzichongfu", nil) toView:_sanainview];
                
                
            }else{
                
                self.model.name =text;
                self.model.localam = [NSString stringWithFormat:@"%@.m4a",text];
                if (self.songURL==nil) {
                    AVURLAsset *videoAsset = (AVURLAsset*)self.avasset;
                    
                    CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
                    CMTime trackDuration =videoAsset.duration;
                    AVMutableComposition *composition =[AVMutableComposition composition];
                    NSMutableArray *audioMixParams = [NSMutableArray array];
                    //获取视频中的音频素材
                    [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
                    
                    //创建一个可变的音频混合
                    AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
                    maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
                    
                    NSString *tmpDir = NSTemporaryDirectory();
                    NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                                [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
                    
                    if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
                        [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
                    }
                    self.musicPath =movDirectory;
                    
                    NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
                    
                    //创建一个输出
                    AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                                     initWithAsset:composition
                                                     presetName:AVAssetExportPresetAppleM4A];
                    exporter.audioMix = maudioMix;
                    exporter.outputFileType=@"com.apple.m4a-audio";
                    exporter.outputURL = exportURL;
                    [exporter exportAsynchronouslyWithCompletionHandler:^{
                        
                        dispatch_async(dispatch_get_main_queue(), ^{
                            NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                                NSURL * outputURL = exporter.outputURL;
                                AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:outputURL options:nil];
                                NSData * data = [NSData dataWithContentsOfFile:movDirectory];
                                NSLog(@"data:%@",data);
                                NSString * tttime =[NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];
                                
                                self.songURL =outputURL;
                                NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                                NSString*path=[paths objectAtIndex:0];
                                NSString * movDirectory =  [path stringByAppendingPathComponent:
                                                            self.model.localam];
                                self.model.url =movDirectory;
                                [self exportPath:movDirectory withFilePath:self.musicPath withobjFilePath:self.model.localam  withStartTime:statr withEndTime:end withBlock:^(BOOL ret) {
                                    
                                    if (ret) {
                                        [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuochengg", nil) toView:_sanainview];
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            __strong __typeof(self) strongSelf = weakself;
                                            [strongSelf->_sanainview removeFromSuperview];
                                            if (_isPlaying) {
                                                
                                                [self.auPlayer pause];
                                                
                                            }
                                           [[NSNotificationCenter defaultCenter] postNotificationName:@"makeaudio"object:@(0)];
                                            [self.navigationController popToRootViewControllerAnimated:YES];
                                            
                                        });
                                        
                                        
                                    }else{
                                        [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuoshibai", nil) toView:_sanainview];
                                        
                                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                            if (_isPlaying) {
                                                
                                                [self.auPlayer pause];
                                                
                                            }
                                            __strong __typeof(self) strongSelf = weakself;
                                            [strongSelf->_sanainview removeFromSuperview];
                                            
                                           
                                            [self.navigationController popToRootViewControllerAnimated:YES];
                                            
                                        });
                                    }
                                    
                                }];
                                
                            }
                        });
                        
                    }];
                }else{
                    
                    NSArray  *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
                    NSString*path=[paths objectAtIndex:0];
                    NSString * movDirectory =  [path stringByAppendingPathComponent:
                                                self.model.localam];
                    
                    [self exportPath:movDirectory withFilePath:self.musicPath withobjFilePath:self.model.localam  withStartTime:statr withEndTime:end withBlock:^(BOOL ret) {
                        
                        if (ret) {
                            [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuochengg", nil) toView:_sanainview];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                __strong __typeof(self) strongSelf = weakself;
                                [strongSelf->_sanainview removeFromSuperview];
                                if (_isPlaying) {
                                    
                                    [self.auPlayer pause];
                                    
                                }
                                
                                [self.navigationController popToRootViewControllerAnimated:YES];
                                
                                
                            });
                        }else{
                            [MBProgressHUD showError:NSLocalizedString(@"lingshengzhizuoshibai", nil) toView:_sanainview];
                            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                                if (_isPlaying) {
                                    
                                    [self.auPlayer pause];
                                    
                                }
                                __strong __typeof(self) strongSelf = weakself;
                                [strongSelf->_sanainview removeFromSuperview];
                                
                                
                                [self.navigationController popToRootViewControllerAnimated:YES];
                                
                                
                            });
                        }
                    }];
                }
                
                
            }
            
        }else{
            [MBProgressHUD showError:NSLocalizedString(@"pleaserut", nil) toView:_sanainview];
            
        }
    };
    
    [self.view addSubview:self->_sanainview];
    
    
    
    
    
    
    
    
}

-(void)palyButtonclick:(UIButton *)sender{
    sender.selected = !sender.selected ;
    if (sender.selected==NO) {
     [self.auPlayer pause];
        return;
        
    }
    if (self.songURL==nil) {
        AVURLAsset *videoAsset = (AVURLAsset*)self.avasset;
        // NSLog(@"AVAsset URL: %@",myAsset.URL);
        CMTime startTime =CMTimeMakeWithSeconds(0,videoAsset.duration.timescale);
        CMTime trackDuration =videoAsset.duration;
        AVMutableComposition *composition =[AVMutableComposition composition];
        NSMutableArray *audioMixParams = [NSMutableArray array];
        //获取视频中的音频素材
        [self setUpAndAddAudioAtPath:videoAsset toComposition:composition start:startTime dura:trackDuration offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
        //
        //创建一个可变的音频混合
        AVMutableAudioMix *maudioMix =[AVMutableAudioMix audioMix];
        maudioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
        
        NSString *tmpDir = NSTemporaryDirectory();
        NSString * movDirectory =  [tmpDir stringByAppendingPathComponent:
                                    [NSString stringWithFormat:@"/%@.m4a",[self getCurrentTimes]]];
        
        if([[NSFileManager defaultManager]fileExistsAtPath:movDirectory]) {
            [[NSFileManager defaultManager]removeItemAtPath:movDirectory error:nil];
        }
        self.musicPath =movDirectory;
        NSURL * exportURL =[NSURL fileURLWithPath:movDirectory];
        
        //创建一个输出
        AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                         initWithAsset:composition
                                         presetName:AVAssetExportPresetAppleM4A];
        exporter.audioMix = maudioMix;
        exporter.outputFileType=@"com.apple.m4a-audio";
        exporter.outputURL = exportURL;
        [exporter exportAsynchronouslyWithCompletionHandler:^{
            
            dispatch_async(dispatch_get_main_queue(), ^{
                NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
                if (exporter.status == AVAssetExportSessionStatusCompleted) {
                    NSURL * outputURL = exporter.outputURL;
                    self.songURL =outputURL;
                    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:outputURL options:nil];
                    NSString * time= [NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];
                    //NSData * data = [NSData dataWithContentsOfFile:movDirectory];
                    
                    _isPlaying = YES;
                    self.playerItem=[[AVPlayerItem alloc]initWithURL:outputURL];
                    self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
                    CMTime currentTime = CMTimeMake(statr, 1);
                    CMTime currentendTime = CMTimeMake(end, 1);
                    
                    [self playMusic];
                    [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
                        
                        
                    }];
                    
                }
            });
            
        }];
    }else{
        self.playerItem=[[AVPlayerItem alloc]initWithURL:self.songURL];
        self.auPlayer = [[AVPlayer alloc]initWithPlayerItem:self.playerItem];
        CMTime currentTime = CMTimeMake(statr, 1);
        CMTime currentendTime = CMTimeMake(end, 1);
        
        [self playMusic];
        [self.auPlayer seekToTime:currentTime toleranceBefore:currentTime toleranceAfter:currentendTime completionHandler:^(BOOL finished) {
            
            
        }];
        
    }
    
    
    
    
}
-(void)playMusic{
    
    [self.auPlayer play];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(playToEnd) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
}
-(void)playToEnd{
    self.auPlayer = nil;
    self.playerItem = nil;
    _isPlaying = NO;
    self.playButton.selected = NO;
    
    
}
-(void)setUpAndAddAudioAtPath:( AVAsset *)songAsset toComposition:(AVMutableComposition*)composition start:(CMTime)start dura:(CMTime)dura offset:(CMTime)offset andArray:(NSMutableArray *)audioMixParams{
    
    
    
    AVMutableCompositionTrack *track = [composition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
    NSArray<AVAssetTrack *> * audioTrackers =[songAsset tracksWithMediaType:AVMediaTypeAudio];
    
    if (0>=audioTrackers.count) {
        return;
    }
    AVAssetTrack *sourceAudioTrack = [audioTrackers objectAtIndex:0];
    
    NSError *error = nil;
    BOOL ok = NO;
    
    CMTime startTime = start;
    CMTime trackDuration = dura;
    CMTimeRange tRange =CMTimeRangeFromTimeToTime(startTime,trackDuration);
    
    
    ok =  [track insertTimeRange:tRange ofTrack:sourceAudioTrack atTime:kCMTimeZero error:&error];
}
-(NSString*)getCurrentTimes{
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    
    // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    [formatter setDateFormat:@"YYYYMMdd_HHmmss"];
    
    //现在时间,你可以输出来看下是什么格式
    
    NSDate *datenow = [NSDate date];
    
    //----------将nsdate按formatter格式转成nsstring
    
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    NSLog(@"currentTimeString =  %@",currentTimeString);
    
    return currentTimeString;
    
}
- (void)exportPath:(NSString *)exportPath

      withFilePath:(NSString *)filePath withobjFilePath:(NSString *)objfilePath


     withStartTime:(float)startTime

       withEndTime:(float)endTime

         withBlock:(success)handle

{
    
    _block = handle;
    
    
    
    NSString *presetName;
    
    NSString *outputFileType;
    
    
    
    if ([filePath.lastPathComponent containsString:@"m4a"]){
        
        
        
        presetName = AVAssetExportPresetAppleM4A;
        
        outputFileType = AVFileTypeAppleM4A;
        
        
        
    }else{
        
        
        
        _block(NO);   return;
        
    }
    
    
    
    // 1.拿到预处理音频文件
    
    NSURL *songURL = [NSURL fileURLWithPath:filePath];
    
    AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
    
    
    
    // 2.创建新的音频文件
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:exportPath]) {
        
        [[NSFileManager defaultManager] removeItemAtPath:exportPath error:nil];
        
    }
    
    
    
    CMTime _startTime = CMTimeMake(startTime*1000, 1000);
    CMTime _stopTime = CMTimeMake(endTime*1000, 1000);
    AVMutableComposition *composition =[AVMutableComposition composition];
    NSMutableArray *audioMixParams = [NSMutableArray array];
    //获取视频中的音频素材
    [self setUpAndAddAudioAtPath:songAsset toComposition:composition start:_startTime dura:_stopTime offset:CMTimeMake(14*44100,44100) andArray:audioMixParams];
    
    //创建一个可变的音频混合
    AVMutableAudioMix *audioMix =[AVMutableAudioMix audioMix];
    audioMix.inputParameters =[NSArray arrayWithArray:audioMixParams];//从数组里取出处理后的音频轨道参数
    
    //创建一个输出
    AVAssetExportSession *exporter =[[AVAssetExportSession alloc]
                                     initWithAsset:composition
                                     presetName:AVAssetExportPresetAppleM4A];
    exporter.audioMix = audioMix;
    exporter.outputFileType=@"com.apple.m4a-audio";
    
    
    if([[NSFileManager defaultManager]fileExistsAtPath:exportPath]) {
        [[NSFileManager defaultManager]removeItemAtPath:exportPath error:nil];
    }
    
    NSURL *exportURL =[NSURL fileURLWithPath:exportPath];
    exporter.outputURL = exportURL;
    FLAudioObject * object = [[FLAudioObject alloc]init];
    object.url = objfilePath;
    object.name = self.model.name;
    object.localam  =self.model.localam;
    
    
    
    __weak typeof(self) weakSelf = self;
    [exporter exportAsynchronouslyWithCompletionHandler:^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        dispatch_async(dispatch_get_main_queue(), ^{
            NSLog(@"Export status not yet completed. Error: %@", exporter.error.description);
            if (exporter.status == AVAssetExportSessionStatusCompleted) {
                NSURL *songURL = [NSURL fileURLWithPath:exportPath];
                
                AVURLAsset *songAsset = [AVURLAsset URLAssetWithURL:songURL options:nil];
                NSString * aac =[NSString stringWithFormat:@"%.2f",CMTimeGetSeconds(songAsset.duration)];
                object.time =[self getMMSSFromSS:(int)CMTimeGetSeconds(songAsset.duration)];
                NSData * data = [NSData dataWithContentsOfFile:exportPath];
                NSLog(@"data:%@",data);
                NSNumber *size;
                [songAsset.URL getResourceValue:&size forKey:NSURLFileSizeKey error:nil];
               
                object.type = 1;
                
                
                if ( [[FLAudioMusicDBManager sharedManager] insertAudioWith:object]) {
                    
                    strongSelf-> _block(YES);
                }else{
                    
                    strongSelf-> _block(NO);
                }
                
            }else{
                
                strongSelf-> _block(NO);
                
            }
        });
        
        
    }];
    
    
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
